﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using WinFormsApp1.MVC.Model;
using WinFormsApp1.MVI.MVIER;

namespace WinFormsApp1.MVI
{
	public partial class MVIForm : Form
	{
		private readonly MviController _controller;

		public MVIForm()
		{
			InitializeComponent();
			_controller = new MviController();
			_controller.StateChanged += UpdateView;
		}


		private void UpdateView(State state)
		{
			this.BeginInvoke(new Action(() =>
			{
				txtName.Text = state.Person.Name;
				txtAge.Text = state.Person.Age.ToString();
				lblResult.Text = state.Message;
				PrintPersonStatus(state.Person); // 打印 Person 状态
			}));
		}
		private void PrintPersonStatus(Person person)
		{
			// 这里可以选择如何显示状态，例如在控制台或标签上
			Debug.WriteLine($"姓名: {person.Name}, 年龄: {person.Age}");

			// 如果要在窗体上显示，可以使用一个标签
			//lblPersonStatus.Text = $"姓名: {person.Name}, 年龄: {person.Age}";
		}
		private void button1_Click(object sender, EventArgs e)
		{
			//_controller.updatemodel();

			Task.Run(() =>
			{
				Thread.Sleep(3000);
				_controller.ProcessIntent(Intent.UpdateName, "已修改" + DateTime.Now);
			});
		}

		private void txtName_TextChanged(object sender, EventArgs e)
		{
			var name = txtName.Text;
			_controller.ProcessIntent(Intent.UpdateName, name);
			_controller.ProcessIntent(Intent.ShowMessage);
		}

		private void txtAge_TextChanged(object sender, EventArgs e)
		{
			if (int.TryParse(txtAge.Text, out var age))
			{
				_controller.ProcessIntent(Intent.UpdateAge, age);
				_controller.ProcessIntent(Intent.ShowMessage);
			}
			else
			{
				MessageBox.Show("请输入有效的年龄！");
			}
		}
	}
}
